#!/bin/bash

storepass=111111
keypass=111111

server_dname="C=CN,ST=GD,L=SZ,O=foo,OU=dev,CN=foo.com"
client_dname="C=CN,ST=GD,L=SZ,O=foo,OU=dev,CN=fooc.com"

keystore_dir=twoway_keys
server_key=$keystore_dir/server.keystore
server_trust_key=$keystore_dir/server_trust.keystore
server_cer=$keystore_dir/server.cer
client_key=$keystore_dir/client.keystore
client_trust_key=$keystore_dir/client_trust.keystore
client_cer=$keystore_dir/client.cer

if [ ! -d $keystore_dir ]; then
    echo "create dir $keystore_dir"
	mkdir -p $keystore_dir
else
    echo "clear dir $keystore_dir"
    rm -r $keystore_dir/*
fi

echo "generate server keystore"
keytool -genkeypair -alias serverkey -keypass $keypass -storepass $storepass \
    -dname $server_dname \
    -keyalg RSA -keysize 2048 -validity 3650 -keystore $server_key
	
echo "generate client keystore"
keytool -genkeypair -alias clientkey -keypass $keypass -storepass $storepass \
    -dname $client_dname \
    -keyalg RSA -keysize 2048 -validity 3650 -keystore $client_key
	
echo "export server certificate"
keytool -exportcert -keystore $server_key -file $server_cer -alias serverkey -storepass $storepass

echo "export client certificate"
keytool -exportcert -keystore $client_key -file $client_cer -alias clientkey -storepass $storepass

echo "add server cert to client trust keystore"
keytool -importcert -keystore $client_trust_key -file $server_cer -alias client_trust_server \
    -storepass $storepass -noprompt
	
echo "add client cert to server trust keystore"
keytool -importcert -keystore $server_trust_key -file $client_cer -alias server_trust_client \
    -storepass $storepass -noprompt